use std::error::Error;
use std::fs; //处理文件相关的函数
use std::env;

pub fn run(config: Config) -> Result<(), Box<dyn Error>> {
    let contents = fs::read_to_string(config.filename)?;

    let results = if config.case_sensitive {
        search(&config.query, &contents)
    } else {
        search_case_insensitive(&config.query, &contents)
    };

    for line in results {
        println!("{}", line);
    }

    println!("===================\nWith content:\n{}", contents);
    Ok(())
}


pub struct Config {
    pub query: String,
    pub filename: String,
    pub case_sensitive: bool,
}

impl Config {
    pub fn new(args: &[String]) -> Result<Config, &'static str> {
        if args.len() < 3 {
            return Err("Not enough arguments");
        }

        Ok(
            Config {
                query: args[1].clone(),
                filename: args[2].clone(),
                //出现 CASE_INSENSITIVE 环境变量，则不区分大小写
                case_sensitive: env::var("CASE_INSENSITIVE").is_err(),
            }
        )
    }
}

//区分大小写
pub fn search<'a>(query: &str, contents: &'a str) -> Vec<&'a str>{
    let mut results = Vec::new();
    
    for line in contents.lines() {
        println!("===== Searching:  {}", line);
        if line.contains(query){
            results.push(line);
        }
    }

    results
}

//不区分大小写
pub fn search_case_insensitive<'a>(query: &str, contents: &'a str) -> Vec<&'a str>{
    let mut results = Vec::new();
    let query = query.to_lowercase();

    for line in contents.lines() {
        println!("===== insensitive Searching:  {}", line);
        if line.to_lowercase().contains(&query){
            results.push(line);
        }
    }

    results
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn one_result() {
        let query = "Rust";
        let contents = "\
        Rust
        is a general-purpose programming language, 
        and aduct, 
        if you will.";

        assert_eq!(vec!["Rust"], search(&query, &contents));
    }
}